<script setup>
/**
 * name：
 * user：sa0ChunLuyu
 * date：2023年6月5日 14:04:22
 */
import {AiEditor} from "aieditor"
import {
  $image, UploadImageAction
} from '~/api'

const $props = defineProps({
  content: {
    type: String,
    default: ''
  },
  height: {
    type: Number,
    default: 600
  }
})

onBeforeUnmount(() => {
  editor && editor.destroy();
})

onMounted(() => {
  createEditor()
})
let editor = null
const createEditor = () => {
  editor = new AiEditor({
    element: editor_ref.value,
    placeholder: "点击输入内容...",
    content: '',
    toolbarKeys: ["undo", "redo", "brush", "eraser",
      "|", "heading", "font-family", "font-size",
      "|", "bold", "italic", "underline", "strike", "link", "code", "subscript", "superscript", "hr", "todo", "emoji",
      "|", "highlight", "font-color",
      "|", "align", "line-height",
      "|", "bullet-list", "ordered-list", "indent-decrease", "indent-increase", "break",
      "|", "image", "quote", "code-block", "table",
      "|", "printer",
      "|", {
        icon: "<img src=\"./aieditor/svg/html.svg\">",
        onClick: (event, editor) => {
          codeMirrorClick()
        },
        tip: "源代码",
      }
    ],
    image: {
      uploader: (file) => {
        return new Promise((resolve, reject) => {
          if (window.FileReader) {
            let reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onloadend = async (e) => {
              const base64 = e.target.result;
              resolve(UploadImageAction({
                base64
              }));
            };
          } else {
            window.$message().error('FileReader不存在');
            reject();
          }
        });
      },
      uploaderEvent: {
        onSuccess: (file, response) => {
          if (response.code !== 200) {
            window.$message().error(response.message);
          }
          return {
            errorCode: response.code === 200 ? 0 : response.code,
            data: {
              src: $image(response.data.url),
              alt: ''
            }
          }
        }
      }
    },
  })
  nextTick(() => {
    editor.setContent($props.content)
  })
}
const code_mirror_content = ref('')
const code_mirror_show = ref(false)
const codeMirrorClick = () => {
  code_mirror_content.value = formatHTML(getContent());
  code_mirror_show.value = true
}

const formatHTML = (htmlString) => {
  let formatted = htmlString.replace(/(<\/[^>]+>)/g, '$1\n');
  formatted = formatted.replace(/(<(?!img)(\w+)[^>]*\/)>/g, '$1\n');
  formatted = formatted.trim();
  return formatted;
}

const codeMirrorClose = () => {
  code_mirror_show.value = false
}
const code_mirror_ref = ref(null)
const codeMirrorRef = (e) => {
  code_mirror_ref.value = e
}
const codeMirrorDone = () => {
  const content = code_mirror_ref.value.getContent()
  editor.setContent(content)
  code_mirror_show.value = false
}

const getContent = () => {
  return editor.getHtml()
}
const getText = () => {
  let text = editor.getText()
  return text.split('\n').join('').replace(/^\s+|\s+$/g, "").slice(0, 200)
}

const editor_ref = ref(null)
const editorRef = (e) => {
  editor_ref.value = e
}

defineExpose({
  getContent,
  getText
})
</script>
<template>
  <div>
    <div>
      <el-dialog v-model="code_mirror_show" title="源代码" width="800px"
                 :close-on-click-modal="false"
                 :close-on-press-escape="false"
                 :show-close="false">
        <div>
          <CodeMirror v-if="code_mirror_show" :ref="codeMirrorRef" :content="code_mirror_content"></CodeMirror>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="codeMirrorClose()">关闭</el-button>
            <el-button @click="codeMirrorDone()" type="primary">确认</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <div class="editor_container_wrapper">
      <div :ref="editorRef" id="editor" :style="{
        height: `${$props.height}px`
      }"></div>
    </div>
  </div>
</template>
<style>
aie-footer {
  display: none;
}
</style>
<style scoped>
#editor {
  width: 100%;
  height: 100%;
}

.editor_container_wrapper {
  width: 800px;
  position: relative;
}
</style>
